var express = require('express');
const Member = require('../models/Member');
const { generateToken } = require('../middlewares/authencation');
var router = express.Router();

/* POST Login. */
router.post('/login', async function(req, res, next) {
    if(!req.body?.username) {
        res.status(402);
        return res.json({code: 'param.error', message: '请填写用户名'});
    }
    const member = await Member.where('username', req.body?.username).first();
    const token = generateToken(member);
    if(!token) {
        res.status(402);
        return res.json({code: 'login.error', message: '用户不存在'});
    }
    member.token = token;
    Member.save({id: member.id, token});
    res.json({member: {
        id: member.id,
        username: member.username,
        avatar: member.avatar,
        gender: member.gender,
        createdAt: member.createdAt,
    }, token});
});

module.exports = router;
